import mysql.connector
from mysql.connector import errorcode
from django.contrib.auth.hashers import make_password, check_password

#连接参数
config = {
    'user': 'root',
    'password': 'P@ssw0rd',
    'database': 'mrqc',
    'host': 'localhost',
}


def connectdb():
    try:
        print('连接mysql数据库...')
        #打开数据库连接
        db = mysql.connector.connect(**config)
        #返回数据库连接
        return db
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("用户名或密码错误")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("数据库不存在")
        else:
            print(err)




def insertdb(db):
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    pwd = make_password("123456")
    # SQL 插入语句
    sql = "insert into mrqc_user(user_id,user_pwd,name,delete_flag) value ('{user_id}','{user_pwd}','{name}','{delete_flag}')".format(user_id=1, user_pwd=pwd, name='管理员', delete_flag='1')

    #sql = "INSERT INTO Student(ID, Name, Grade) \
    #    VALUES ('%s', '%s', '%d')" % \
    #    ('001', 'HP', 60)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except mysql.connector.Error as err:
        # Rollback in case there is any error
        print(err)
        db.rollback()


db = connectdb()
insertdb(db)
